package com.panpa.yellcall;

import android.*;
import android.content.*;
import android.content.pm.*;
import android.hardware.*;
import android.hardware.Camera.*;
import android.media.*;
import android.net.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.preference.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.hardware.camera2.*;
import android.annotation.*;
import android.support.annotation.*;
import android.app.*;

public class MainActivity extends AppCompatActivity 
{
	private static final String TAG = "AudioRecord";
    static final int SAMPLE_RATE_IN_HZ = 8000;
    static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
    AudioRecord mAudioRecord;
    boolean isGetVoiceRun;
    Object mLock;
	private  boolean a = false;

	private Camera camera;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		 Button button2=(Button) findViewById(R.id.mainButton2);
		 
		SharedPreferences sharedPreferences = getSharedPreferences("FirstRun",0);
		Boolean first_run = sharedPreferences.getBoolean("First",true);
		if (first_run){
			sharedPreferences.edit().putBoolean("First",false).commit();
			android.support.v7.app.AlertDialog dialog;
			android.support.v7.app.AlertDialog.Builder builder =new android.support.v7.app.AlertDialog.Builder(this)
				.setTitle("使用需知")    //设置对话框的标题
				.setMessage("本软件不收集您然后隐私，请放心给予权限。如果您需要APP在后台响应，最好将其放置在后台白名单中。")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

					}
				});
			dialog = builder.create();
			dialog.show();
		}

		 
		
		 
		 
		button2.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					// TODO: Implement this method
					Intent intent=new Intent(MainActivity.this,Setting.class);
					startActivity(intent);
				}
			});
		mLock = new Object();
		if (isGetVoiceRun) {
			Log.e(TAG, "还在录着呢");
			return;
		}
		mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
									   SAMPLE_RATE_IN_HZ, AudioFormat.CHANNEL_IN_DEFAULT,
									   AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE);
		if (mAudioRecord == null) {
			Log.e("sound", "mAudioRecord初始化失败");
		}
		isGetVoiceRun = true;

		new Thread(new Runnable() {


				@Override
				public void run() {
					mAudioRecord.startRecording();
					short[] buffer = new short[BUFFER_SIZE];
					while (isGetVoiceRun) {
						//r是实际读取的数据长度，一般而言r会小于buffersize
						int r = mAudioRecord.read(buffer, 0, BUFFER_SIZE);
						long v = 0;
						// 将 buffer 内容取出。进行平方和运算
						for (int i = 0; i < buffer.length; i++) {
							v += buffer[i] * buffer[i];
						}
						// 平方和除以数据总长度，得到音量大小。
						double mean = v / (double) r;
						
						double volume = 10 * Math.log10(mean);
						Message msg = new Message();
						msg.what = (int)volume;
						handler.sendMessage(msg);

						//Log.d(TAG, "分贝值:" + volume);
						// 大概一秒十次
						synchronized (mLock) {
							try {
								mLock.wait(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
					mAudioRecord.stop();
					mAudioRecord.release();
					mAudioRecord = null;
				}
			}).start();
		 }
		 
		 
	Handler handler = new Handler(){

		private Button button;

		

		
		
		public void handleMessage(Message msg) {
			int yell=msg.what;
			TextView bd=(TextView) findViewById(R.id.mainTextView1);
			 button=(Button) findViewById(R.id.mainButton1);
			SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

			if (a == true && yell >= Integer.parseInt(prefs.getString("pref_db","50"))){
				switch(prefs.getString("pre_sta","flashlight"))
				{
					case "flashlight": 
						
						changeFlashLight(true);
						/**if (camera == null) {
							camera = Camera.open();
						}
						camera.startPreview();
						Parameters parameter = camera.getParameters();
						parameter.setFlashMode(Parameters.FLASH_MODE_TORCH);
						camera.setParameters(parameter);
						**/break;
						case "vib":
						Vibrator vib = (Vibrator) MainActivity.this.getSystemService(Service.VIBRATOR_SERVICE);
						if(a)
							{
								vib.vibrate( new long[]{100, 50, 100, 50, 50, 100}, false ? 1 : -1);
							}
							else{
								vib.cancel();
								
							}
							break;
						case "APP":
						
						PackageManager packageManager = getPackageManager();   
						Intent intent=new Intent();   
						intent =packageManager.getLaunchIntentForPackage(prefs.getString("packageName","null"));
						if(intent==null)
							{
								Toast.makeText(MainActivity.this,"还未选择启动的APP" ,Toast.LENGTH_SHORT).show();
							}
						else{
							   
						startActivity(intent);}
							break;
							case"call":
						callPhone(prefs.getString("pre_num","10086"));
								break;
				}
				
			}
			/**
				
			
			
		}
		**/	button.setOnClickListener(new OnClickListener(){



					@Override
					public void onClick(View p1)
					{
						if(a == false){
							a=true;
							button.setText("关闭");
						}
						else{
							a=false;
							changeFlashLight(a);
							button.setText("开启");
						}
						// TODO: Implement this method
					}
				});
			
			bd.setText("当前环境分贝:" + yell);
		};
	
	
};
	public void callPhone(String phoneNum){

        //android6版本获取动态权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.CALL_PHONE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        //如果需要手动拨号将Intent.ACTION_CALL改为Intent.ACTION_DIAL（跳转到拨号界面，用户手动点击拨打）
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }
	
	
	@TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void changeFlashLight(boolean openOrClose) {
        //判断API是否大于24（安卓7.0系统对应的API）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                //获取CameraManager
                CameraManager mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
                //获取当前手机所有摄像头设备ID
                String[] ids  = mCameraManager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
                    //查询该摄像头组件是否包含闪光灯
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
                    if (flashAvailable != null && flashAvailable
						&& lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                        //打开或关闭手电筒
                        mCameraManager.setTorchMode(id, openOrClose);
                    }
                }
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }else
		{
			if(openOrClose)
				{
					if (camera == null) {
						camera = Camera.open();
					}
					camera.startPreview();
					Parameters parameter = camera.getParameters();
					parameter.setFlashMode(Parameters.FLASH_MODE_TORCH);
					camera.setParameters(parameter);
					
				}if(!openOrClose){

					if (camera != null) {
						Parameters parameter = camera.getParameters();
						parameter.setFlashMode(Parameters.FLASH_MODE_OFF);
						camera.setParameters(parameter);
					}}
				
		}
    }
	
	
	
	
	@Override
    public void onDestroy() {
        super.onDestroy();
        camera.release();
    }
}
